/*
 * Programmer	:	Muhammad Mohsin Mughal
 * Project	 	:  	Travel Experts Phase 3 (Agent Management)
 * Language  	:  	Java
 * Date Written	:   March 20, 2011.
 * Student Id	:	559933	
 */


import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class AgentPanel extends javax.swing.JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JScrollPane jScrollPane1;
	private JTextField txtAgPos;
	private JTextField txtAgEmail;
	private JTextField txtAgBPhone;
	private JTextField txtAgLName;
	private JTextField txtAgMName;
	private JTextField txtAgFName;
	private JTextField txtAgId;
	private JLabel lblAgAgency;
	private JLabel lblAgPos;
	private JLabel lblAgEmail;
	private JLabel lblAgBPhone;
	private JLabel lblAgMName;
	private JComboBox cbAgentAct;
	private JLabel lblAgAct;
	private JComboBox cbAgencyId;
	private JLabel lblUpdate;
	private JButton btnClear;
	private JButton btnEdit;
	private JButton btnSave;
	private JLabel lblAgLName;
	private JLabel lblAgFName;
	private JLabel lblAgId;
	private JLabel jLabel1;
	private JTable agtTable;
	private Connection conn;
	private Statement stmt;
	private ResultSet rs;
	JDialog d = new JDialog();
	private JLabel lblFNameErrMsg;
	DefaultTableModel tblAgentsModel = new DefaultTableModel();
	int updatedrows;
	boolean AddMode = true;
	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	*/
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.getContentPane().add(new AgentPanel());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
	
	public AgentPanel()
	{
		super();
		initGUI();
		try
		{
			// Generate Tables
			
			loadtable();
		} 
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// function to  fill data in the Agent table
	public void loadtable() throws SQLException
	{
		 while (agtTable.getRowCount() > 0)
		 {
			  ((DefaultTableModel)agtTable.getModel()).removeRow(0);
		 }
		stmt=Database_Functions.databaseConnection();
		rs = stmt.executeQuery("select * from Agents");
		ResultSetMetaData rsmd = rs.getMetaData();
		String [] header=new String[rsmd.getColumnCount()];
		for(int j=1;j<=rsmd.getColumnCount();j++)
		{
			header[j-1]=rsmd.getColumnLabel(j);
		}
		while(rs.next())
		{
			
			Agents agt = new Agents();
			agt.setagentId(rs.getInt(1));
			agt.setagentFirstName(rs.getString(2));
			agt.setagentMiddleName(rs.getString(3));
			agt.setagentLastName(rs.getString(4));
			agt.setagtBusPhone(rs.getString(5));
			agt.setagentEmail(rs.getString(6));
			agt.setagentPosition(rs.getString(7));
			agt.setagentAgency(rs.getInt(8));
			agt.setagentStatus(rs.getString(9));
			Object [] myAgt = { agt.getagentId(),agt.getagentFirstName(),agt.getagentMiddleName(),
								agt.getagentLastName(),agt.getagtBusPhone(),agt.getagentEmail(),
								agt.getagentPosition(),agt.getagentAgency(),agt.getagentStatus()};
			tblAgentsModel.addRow(myAgt);
			
			
		}
		
		Enumeration<TableColumn> cols = agtTable.getColumnModel().getColumns();
		int i=0;
		while (cols.hasMoreElements())
		{
			TableColumn col = cols.nextElement();
			col.setHeaderValue(header[i++]);
		}
	
		//conn.close();
		
	}
	
	// build the Graphic user interface
	
	private void initGUI() {
		try 
		{
			setPreferredSize(new Dimension(999, 658));
			this.setLayout(null);
			{
				jScrollPane1 = new JScrollPane();
				this.add(jScrollPane1);
				jScrollPane1.setBounds(18, 45, 937, 187);
				{
					
					agtTable = new JTable();
					jScrollPane1.setViewportView(agtTable);
					agtTable.setModel(tblAgentsModel);
					agtTable.setBounds(25, 46, 597, 87);
					tblAgentsModel.setColumnCount(9);
					agtTable.addKeyListener(new KeyListener() {
						
						@Override
						public void keyTyped(KeyEvent e) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void keyReleased(KeyEvent e) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void keyPressed(KeyEvent e) {
							// TODO Auto-generated method stub
							if(e.getKeyCode()==KeyEvent.VK_DOWN)
							{
								if(agtTable.getRowCount()>agtTable.getSelectedRow()+1)
								{
									try 
									{
										populateForm(agtTable.getSelectedRow()+1);
									} 
									catch (ParseException e1)
									{
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}
								}
							}
							else if(e.getKeyCode()==KeyEvent.VK_UP) 
							{
								if(agtTable.getSelectedRow()==0)
								{
									return;
								}
								if(agtTable.getSelectedRow() <= agtTable.getRowCount()-1)
								{
									try 
									{
										populateForm(agtTable.getSelectedRow()-1);
									}
									catch (ParseException e1) 
									{
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}
								}
								
							}
							
						}
					});
					// Mouse Clicked Listener
					agtTable.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent e) 
						{
							// TODO Auto-generated method stub
							super.mouseClicked(e);
							try
							{
								populateForm(agtTable.getSelectedRow());
								AddMode = false;
								
							} 
							catch (ParseException e1) 
							{
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					});
					
				}
			}
		//	Add components to JPanel
			{
				jLabel1 = new JLabel();
				this.add(jLabel1);
				jLabel1.setText("Agent Maintenance");
				jLabel1.setBounds(385, 12, 294, 23);
				jLabel1.setFont(new java.awt.Font("Abyssinica SIL",1,24));
			}
			{
				lblAgId = new JLabel();
				this.add(lblAgId);
				lblAgId.setText("Agent Id:");
				lblAgId.setBounds(12, 241, 60, 26);
			}
			{
				lblAgFName = new JLabel();
				this.add(lblAgFName);
				lblAgFName.setText("Agent First Nm:");
				lblAgFName.setBounds(7, 289, 107, 14);
			}
			{
				lblAgMName = new JLabel();
				this.add(lblAgMName);
				lblAgMName.setText("Agent Middle Ini:");
				lblAgMName.setBounds(7, 323, 117, 14);
			}
			{
				lblAgLName = new JLabel();
				this.add(lblAgLName);
				lblAgLName.setText("Agent Last Nm:");
				lblAgLName.setBounds(7, 356, 105, 14);
			}
			{
				lblAgBPhone = new JLabel();
				this.add(lblAgBPhone);
				lblAgBPhone.setText("Agent Bus Ph:");
				lblAgBPhone.setBounds(7, 387, 105, 14);
			}
			{
				lblAgEmail = new JLabel();
				this.add(lblAgEmail);
				lblAgEmail.setText("Agent Email:");
				lblAgEmail.setBounds(7, 428, 80, 14);
			}
			{
				lblAgPos = new JLabel();
				this.add(lblAgPos);
				lblAgPos.setText("Agent Position:");
				lblAgPos.setBounds(7, 478, 105, 14);
			}
			{
				lblAgAgency = new JLabel();
				this.add(lblAgAgency);
				lblAgAgency.setText("Agent Agency:");
				lblAgAgency.setBounds(583, 310, 88, 14);
			}
			{
				txtAgId = new JTextField();
				this.add(txtAgId);
				txtAgId.setBounds(155, 244, 284, 21);
				txtAgId.setEnabled(false);
			}
			{
				txtAgFName = new JTextField();
				this.add(txtAgFName);
				txtAgFName.setBounds(158, 286, 281, 21);
			}
			{
				txtAgMName = new JTextField();
				this.add(txtAgMName);
				txtAgMName.setBounds(158, 319, 281, 22);
			}
			{
				txtAgLName = new JTextField();
				this.add(txtAgLName);
				txtAgLName.setBounds(158, 353, 281, 21);
			}
			{
				txtAgBPhone = new JTextField();
				this.add(txtAgBPhone);
				txtAgBPhone.setBounds(158, 392, 281, 21);
			}
			{
				txtAgEmail = new JTextField();
				this.add(txtAgEmail);
				txtAgEmail.setBounds(158, 425, 281, 21);
			}
			{
				txtAgPos = new JTextField();
				this.add(txtAgPos);
				txtAgPos.setBounds(158, 471, 281, 21);
			}
			{
				// Save Button to Add new Records in the Agent Table
				
				btnSave = new JButton();
				this.add(btnSave);
				btnSave.setText("Add");
				btnSave.setBounds(87, 535, 159, 62);
			//	btnSave.setEnabled(false);
				btnSave.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent evt) {
						System.out.println("btnSave.mouseClicked, event="+evt);
						//TODO add your code for btnSave.mouseClicked
						if ( ! validData())
						{
							
							JOptionPane.showMessageDialog(AgentPanel.this, lblFNameErrMsg.getText());
						}
						else if (cbAgentAct.getSelectedItem().equals("Inactive")) {
							
							JOptionPane.showMessageDialog(AgentPanel.this, "New Agent Cannot be Inactive");
						}
						else if (! AddMode) {
							
							JOptionPane.showMessageDialog(AgentPanel.this, "Record Already Exist");
						}
						else 
							
						{
					
							stmt = Database_Functions.databaseConnection();
						
					
						String insertSql = "Insert Into AGENTS (AGENTID,AGTFIRSTNAME, AGTMIDDLEINITIAL, AGTLASTNAME, AGTBUSPHONE, AGTEMAIL, AGTPOSITION, AGENCYID,AGENTSTATUS)" 
								+ "Values(S_101_1_AGENTS.nextval, '"+txtAgFName.getText()+"', '"+txtAgMName.getText()+"', '"
								+txtAgLName.getText()+"', '"+txtAgBPhone.getText()+"', '"+txtAgEmail.getText()+"', '"+txtAgPos.getText()+"', "+cbAgencyId.getSelectedItem()+",'"+cbAgentAct.getSelectedItem()+"')";
										
												
						System.out.println("insert button");
						try
						{
							//System.out.println(strSQL);
							stmt.executeUpdate(insertSql);
							loadtable();
							clearFields();
						} 
						catch (SQLException e1) 
						{
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
							
					}
					}

					// validate the data before Entering the record. Make sure all 
					// fields are written 
					private boolean validData() {
						// TODO Auto-generated method stub
						if (txtAgFName.getText().equals(""))
						{
							lblFNameErrMsg = new JLabel("You must Enter First Name ");
							return false;
						}
						else if (txtAgLName.getText().equals(""))
						{
							lblFNameErrMsg = new JLabel("You must Enter Last Name ");
							return false;
						}
						else if (txtAgBPhone.getText().equals(""))
						{
							lblFNameErrMsg = new JLabel("You must Enter Business Phone Numnber ");
							return false;
						}
						else if (txtAgEmail.getText().equals(""))
						{
							lblFNameErrMsg = new JLabel("You must Enter Email of the Agent ");
							return false;
						}
						else if (txtAgPos.getText().equals(""))
						{
							lblFNameErrMsg = new JLabel("You must Enter Agent Position ");
							return false;
						}
						else if (cbAgencyId.getSelectedItem().equals("Select Any Item"))
						{
							lblFNameErrMsg = new JLabel("You must Select Agent Agency ");
							return false;
						}
						else if (cbAgentAct.getSelectedItem().equals("Select Any Item"))
						{
							lblFNameErrMsg = new JLabel("You must Select Agent Status ");
							return false;
						}
						return true;
						
					}
				});
			}
			
			{
				// Clear the fields
				
				btnClear = new JButton();
				this.add(btnClear);
				btnClear.setText("Clear");
				btnClear.setBounds(775, 537, 145, 60);
				btnClear.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent evt) {
						System.out.println("btnClear.mouseClicked, event="+evt);
						//TODO add your code for btnClear.mouseClicked
						clearFields();
						
						
					}
				});

			}
			// Edit the Agent Record
			{
				btnEdit = new JButton();
				this.add(btnEdit);
				btnEdit.setBounds(434, 539, 145, 58);
				btnEdit.setText("Edit");
				btnEdit.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent evt) {
						System.out.println("btnEdit.mouseClicked, event="+evt);
						//TODO add your code for btnEdit.mouseClicked
						
						/* if we are change the status of agent to inactive it will allow
						 to assign the customers of this inactive agent to some other 
						 active agent.*/
						// Update Inactive Agent
						if (cbAgentAct.getSelectedItem().equals("Inactive"))
						{
							
							JOptionPane.showMessageDialog(AgentPanel.this, "You have to Assign attached customers to other Active Agents");
							CustomerAgtDialog custDlg=new CustomerAgtDialog(AgentPanel.this,AgentPanel.this.txtAgId.getText());
							custDlg.setModal(true);
							custDlg.setVisible(true);
							txtAgFName.setEnabled(true);
							txtAgMName.setEnabled(true);
							txtAgLName.setEnabled(true);
							txtAgBPhone.setEnabled(true);
							txtAgEmail.setEnabled(true);
							txtAgPos.setEnabled(true);
							btnSave.setEnabled(true);
							stmt=Database_Functions.databaseConnection();
							String updstr = "update AGENTS set AGTFIRSTNAME ='" +txtAgFName.getText() + "' ,AGTMIDDLEINITIAL='" + txtAgMName.getText()
							+ "' ,AGTLASTNAME='" +txtAgLName.getText()
							+ "' ,AGTBUSPHONE='" +txtAgBPhone.getText()
							+ "' ,AGTEMAIL='" +txtAgEmail.getText()
							+ "' ,AGTPOSITION='" +txtAgPos.getText()
							+ "' ,AGENTSTATUS='" +cbAgentAct.getSelectedItem() 
							+ "' ,AGENCYID='" +cbAgencyId.getSelectedItem()+"'"
							+ "where AGENTID =" + txtAgId.getText();
							try {
								updatedrows = stmt.executeUpdate(updstr);
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (updatedrows > 0)
							{
								lblUpdate.setText("Agent " + txtAgFName.getText() +  " updated successfully");
							}
							// after saving data it enable edit button to edit another agent record and 
							// disable save button and initialize all fields to blank
							
							btnEdit.setEnabled(true);
							//		btnSave.setEnabled(false);
							txtAgId.setText("");
							txtAgFName.setText("");
							txtAgMName.setText("");
							txtAgLName.setText("");
							txtAgBPhone.setText("");
							txtAgEmail.setText("");
							txtAgPos.setText("");
							cbAgentAct.setSelectedIndex(0);
							cbAgencyId.setSelectedIndex(0);
							try {
								loadtable();
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							System.out.println("return to main");
							
							
						}
						else
						{
							// Update Active Agent
							
							txtAgFName.setEnabled(true);
							txtAgMName.setEnabled(true);
							txtAgLName.setEnabled(true);
							txtAgBPhone.setEnabled(true);
							txtAgEmail.setEnabled(true);
							txtAgPos.setEnabled(true);
							//		txtAgAgency.setEnabled(true);
							btnSave.setEnabled(true);
							stmt=Database_Functions.databaseConnection();
							String updstr = "update AGENTS set AGTFIRSTNAME ='" +txtAgFName.getText() + "' ,AGTMIDDLEINITIAL='" + txtAgMName.getText()
							+ "' ,AGTLASTNAME='" +txtAgLName.getText()
							+ "' ,AGTBUSPHONE='" +txtAgBPhone.getText()
							+ "' ,AGTEMAIL='" +txtAgEmail.getText()
							+ "' ,AGTPOSITION='" +txtAgPos.getText()
							+ "' ,AGENTSTATUS='" +cbAgentAct.getSelectedItem() 
							+ "' ,AGENCYID='" +cbAgencyId.getSelectedItem()+"'"
							+ "where AGENTID =" + txtAgId.getText();
							try {
								updatedrows = stmt.executeUpdate(updstr);
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (updatedrows > 0)
							{
								lblUpdate.setText("Agent " + txtAgFName.getText() +  " updated successfully");
							}
							// after saving data it enable edit button to edit another agent record and 
							// disable save button and initialize all fields to blank
							
							btnEdit.setEnabled(true);
							//		btnSave.setEnabled(false);
							txtAgId.setText("");
							txtAgFName.setText("");
							txtAgMName.setText("");
							txtAgLName.setText("");
							txtAgBPhone.setText("");
							txtAgEmail.setText("");
							txtAgPos.setText("");
							cbAgentAct.setSelectedIndex(0);
							cbAgencyId.setSelectedIndex(0);
							try {
								loadtable();
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				});
			}
			{
				lblUpdate = new JLabel();
				this.add(lblUpdate);
				lblUpdate.setBounds(481, 411, 241, 17);
			}
			{
				ComboBoxModel cbAgencyIdModel = 
					new DefaultComboBoxModel(getAgencyId());
							
				cbAgencyId = new JComboBox();
				this.add(cbAgencyId);
				this.add(getLblAgAct());
				this.add(getCbAgentAct());
				cbAgencyId.setModel(cbAgencyIdModel);
				cbAgencyId.setBounds(787, 304, 127, 21);
				
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	// populate the agencyId ComboBox
	
	private Vector getAgencyId() {
		// TODO Auto-generated method stub
		stmt=Database_Functions.databaseConnection();
		Vector<String> agency = new Vector<String>();
		
		agency.add("Select Any Item");
		try {
			rs = stmt.executeQuery("select distinct(agencyid) from Agents");
			while (rs.next())
			{
				agency.add(rs.getString("agencyid"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*try {
			//conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	*/	
		return agency;
	}

	// display columns of selected agent into the text fields
	private void populateForm(int row) throws ParseException 
	{
		// TODO Auto-generated method stub
		
		String [] fields=new String[agtTable.getColumnCount()];
		
		for(int i=0;i<agtTable.getColumnCount();i++)
		{
			fields[i]=""+tblAgentsModel.getValueAt(agtTable.getSelectedRow(), i);
		}
		
			txtAgId.setText(fields[0]);
			txtAgFName.setText(fields[1]);
			txtAgMName.setText(fields[2]);
			txtAgLName.setText(fields[3]);
			txtAgBPhone.setText(fields[4]);
			txtAgEmail.setText(fields[5]);
			txtAgPos.setText(fields[6]);
			cbAgencyId.setSelectedItem(fields[7]);
			cbAgentAct.setSelectedItem(fields[8]);
			
				
		}
	
	public void clearFields()
	{
		txtAgId.setText("");
		txtAgFName.setText("");
		txtAgMName.setText("");
		txtAgLName.setText("");
		txtAgBPhone.setText("");
		txtAgEmail.setText("");
		txtAgPos.setText("");
	//	txtAgAgency.setText("");
		lblUpdate.setText("");
		cbAgencyId.setSelectedIndex(0);
		AddMode = true;
		
		
	}
	
	private JLabel getLblAgAct() {
		if(lblAgAct == null) {
			lblAgAct = new JLabel();
			lblAgAct.setText("Agent Act/DAct");
			lblAgAct.setBounds(579, 256, 106, 14);
		}
		return lblAgAct;
	}
	
	private JComboBox getCbAgentAct() {
		if(cbAgentAct == null) {
			ComboBoxModel cbAgentActModel = 
				new DefaultComboBoxModel(
						new String[] { "Select Any Item","Active", "Inactive" });
			cbAgentAct = new JComboBox();
			cbAgentAct.setModel(cbAgentActModel);
			cbAgentAct.setBounds(787, 256, 127, 21);
		}
		return cbAgentAct;
	}


}
